<?php
namespace app\controller\common;

use think\Controller;
use GuzzleHttp\Client;
use app\model\Book;

class BookController extends Controller
{	

	public $url = 'https://www.qidian.com/finish?orderId=11&page=';
	public $info_url = 'https://book.qidian.com/ajax/comment/index?[id]&bookId=[bookId]';
	public $page = 10;

	public function indexAction()
	{
		// &#100066;&#100060;&#100065;&#100056;&#100060;&#100065;
		// ([&#][0-9]{6}\;){1,10}

		$client = new Client();
		$ids = [];
		$ids = Book::column('book_id');
		for ($i=1; $i < $this->page+1; $i++) { 
			$url = $this->url.$i;
			$response = $client->request('GET', $url,['verify'=>false]);
			$bodys = $response->getBody();
			preg_match_all("/book-mid-info\".*data-bid=\"([0-9]*)\">(.*)<\/a>.*qd_B59\".*>(.*)<\/a>.*qd_B60\">(.*)<\/a>.*qd_B61\">(.*)<\/a>.*intro\">(.*)<\/p>/isU",$bodys,$body);
			if(!empty($body[1]) && count($body[1]>0)){
				$book = new Book;
				$data = [];
				foreach ($body[1] as $key => $value) {
					
					if(!in_array($value,$ids)){
						$data[] = [
							'book_id' 	=> $value,
							'name'		=> $body[2][$key],
							'author'	=> $body[3][$key],
							'type'		=> $body[4][$key],
							'sub_type'	=> $body[5][$key],
						];
					}
				}
				$book->saveAll($data);
			}
		}
		

	}

	public function updateAction()
	{
		$client = new Client();
		$url = $this->url.'1';
		$response = $client->request('GET', $url,['verify'=>false]);
		preg_match("/_csrfToken=[a-zA-Z\d]{40}/isU",$response->getHeaderLine('set-cookie'),$cookies);
		if(empty($cookies[0])){
			return '缓存获取失败';
		}
		$param['url'] = $this->info_url;
		$param['id'] = $cookies[0];
		Book::where(['rate'=>0])->chunk(100, function($books)use($param) {
			$client = new Client();
    		foreach ($books as $book) {
				$url = str_replace(['[id]','[bookId]'],[$param['id'],$book->book_id], $param['url']);
				$response = $client->request('GET', $url,['verify'=>false]);
				$content = json_decode($response->getBody()->getContents(),true);
				if(!empty($content['data']['rate'])){
					$book->rate = $content['data']['rate'];
					$book->save();
				}
    		}
		});
	}
}
